package com.sc.admin.web.controller;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import org.cleverframe.fastdfs.client.StorageClient;
import org.cleverframe.fastdfs.model.StorePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FileController {
	@Autowired
	private StorageClient storageClient;
	@Value("${fileupload.FastDFS.storage}")
	private String address;

	@RequestMapping("/upload")
	public @ResponseBody Object upload(MultipartFile imgFile) {
		// 我们已经拿到文件流了，我们要调用fastdfs-client将这个文件流传到服务器上
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String ext = FilenameUtils.getExtension(imgFile.getOriginalFilename());
			StorePath sp = storageClient.uploadFile(imgFile.getInputStream(), imgFile.getSize(), ext, null);
			String path = sp.getPath();
			StringBuilder sb = new StringBuilder(address);
			map.put("error", 0);
			map.put("url", sb.append(path).toString());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("error", 1);
			map.put("message", "文件上传异常");
		}
		return map;
	}
}
